'use strict';
const db = uniCloud.database();

exports.main = async (event, context) => {
  console.log('开始测试聊天功能...');
  
  try {
    // 1. 先清理可能存在的测试数据
    try {
      await db.collection('chatMessages')
        .where({
          $or: [
            { senderId: 'test_user_001' },
            { receiverId: 'test_user_001' },
            { senderId: 'test_user_002' },
            { receiverId: 'test_user_002' }
          ]
        })
        .remove();
      console.log('清理旧的测试数据完成');
    } catch (cleanError) {
      console.log('清理数据时出错:', cleanError);
    }
    
    // 2. 创建测试用户聊天消息
    const testMessages = [
      {
        type: 'text',
        senderId: 'test_user_001',
        senderNickname: '张同学',
        senderAvatar: '',
        receiverId: 'admin',
        receiverNickname: '客服小助手',
        receiverAvatar: '',
        content: '你好，我想咨询一下关于代购的问题',
        createTime: new Date(Date.now() - 300000), // 5分钟前
        status: 'unread'
      },
      {
        type: 'text',
        senderId: 'test_user_002',
        senderNickname: '李小明',
        senderAvatar: '',
        receiverId: 'admin',
        receiverNickname: '客服小助手',
        receiverAvatar: '',
        content: '请问代购服务怎么使用？',
        createTime: new Date(Date.now() - 600000), // 10分钟前
        status: 'unread'
      },
      {
        type: 'text',
        senderId: 'admin',
        senderNickname: '客服小助手',
        senderAvatar: '',
        receiverId: 'test_user_001',
        receiverNickname: '张同学',
        receiverAvatar: '',
        content: '您好！我是客服小助手，很高兴为您服务',
        createTime: new Date(Date.now() - 280000), // 4.5分钟前
        status: 'sent'
      },
      {
        type: 'text',
        senderId: 'test_user_001',
        senderNickname: '张同学',
        senderAvatar: '',
        receiverId: 'admin',
        receiverNickname: '客服小助手',
        receiverAvatar: '',
        content: '我想让人帮我代购一些学习用品，但不知道怎么发布任务',
        createTime: new Date(Date.now() - 120000), // 2分钟前
        status: 'unread'
      }
    ];
    
    // 批量插入测试消息
    const insertResult = await db.collection('chatMessages').add(testMessages);
    console.log('测试消息插入成功:', insertResult);
    
    // 2. 测试 adminChat 云函数的各个功能
    
    // 测试获取用户列表
    console.log('测试获取用户列表...');
    const userListResult = await uniCloud.callFunction({
      name: 'adminChat',
      data: {
        action: 'getUserList',
        page: 1,
        pageSize: 10
      }
    });
    console.log('用户列表结果:', userListResult.result);
    
    // 测试获取消息
    console.log('测试获取消息...');
    const messagesResult = await uniCloud.callFunction({
      name: 'adminChat',
      data: {
        action: 'getMessages',
        userId: 'test_user_001',
        page: 1,
        pageSize: 20
      }
    });
    console.log('消息列表结果:', messagesResult.result);
    
    // 测试发送消息
    console.log('测试发送消息...');
    const sendResult = await uniCloud.callFunction({
      name: 'adminChat',
      data: {
        action: 'sendMessage',
        userId: 'test_user_001',
        content: '这是一条测试回复消息',
        type: 'text'
      }
    });
    console.log('发送消息结果:', sendResult.result);
    
    return {
      code: 200,
      msg: '聊天功能测试完成',
      data: {
        insertedMessages: testMessages.length,
        userListTest: userListResult.result.code === 200,
        messagesTest: messagesResult.result.code === 200,
        sendMessageTest: sendResult.result.code === 200
      }
    };
    
  } catch (error) {
    console.error('测试失败:', error);
    return {
      code: 500,
      msg: '测试失败',
      error: error.message
    };
  }
};
